/*
 * Debts Manager. Simple android application for managing debts.
 * Copyright (C) 2010 Maxim Manuylov
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
 */

package manuylov.maxim.dm.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import manuylov.maxim.common.util.Pair;
import manuylov.maxim.dm.Constants;
import manuylov.maxim.dm.R;
import manuylov.maxim.dm.data.DataManager;
import manuylov.maxim.dm.data.util.DataActionResultProcessor;
import manuylov.maxim.dm.data.util.DataProcessor;
import manuylov.maxim.dm.data.util.DataUtil;
import manuylov.maxim.dm.view.ImprovedAutoCompleteTextEdit;

import java.util.List;

public class NewRecord extends BaseDMActivity {
    private final static String PROPERTY_PERSON = "person";
    private final static String PROPERTY_QUANTITY = "quantity";
    private final static String PROPERTY_SUBJECT = "subject";
    private final static String PROPERTY_COMMENT = "comment";

    private int myRecordType;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_record);

        processIntent();

        final SharedPreferences sharedPreferences = getApplicationPreferences();

        final ImprovedAutoCompleteTextEdit personEditor = (ImprovedAutoCompleteTextEdit) findViewById(R.id.person_editor);
        personEditor.asTextView().setHint(sharedPreferences.getString(Constants.DEFAULT_PERSON, ""));

        final ImprovedAutoCompleteTextEdit subjectEditor = (ImprovedAutoCompleteTextEdit) findViewById(R.id.subject_editor);
        subjectEditor.asTextView().setHint(sharedPreferences.getString(Constants.DEFAULT_SUBJECT, ""));

        doRestoreState(savedInstanceState);

        DataUtil.perfromDataAction(this, R.string.loading, new DataProcessor<Pair<List<String>, List<String>>>() {
            public Pair<List<String>, List<String>> process(final DataManager dataManager) {
                return Pair.create(getAllPersons(dataManager), dataManager.getAllSubjects());
            }
        }, new DataActionResultProcessor<Pair<List<String>, List<String>>>() {
            public Void process(final Pair<List<String>, List<String>> pair) {
                setAutoCompleteAdapter(personEditor, pair.getFirst());
                setAutoCompleteAdapter(subjectEditor, pair.getSecond());
                return null;
            }
        });

        final Button okPlusButton = (Button) findViewById(R.id.ok_plus_button);
        okPlusButton.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                saveRecord(true);
            }
        });

        final Button okButton = (Button) findViewById(R.id.ok_button);
        okButton.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                saveRecord(false);
            }
        });

        final Button cancelButton = (Button) findViewById(R.id.cancel_button);
        cancelButton.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                finish();
            }
        });
    }

    private void processIntent() {
        final Intent intent = getIntent();

        myRecordType = getIntOrFinish(intent, Constants.NEW_RECORD_TYPE);

        setTitle(intent);

        final TextView toFromTextView = (TextView) findViewById(R.id.to_from_label);
        toFromTextView.setText(getIntOrFinish(intent, Constants.TO_FROM_LABEL_TEXT));
    }

    @Override
    protected void onRestoreInstanceState(final Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        doRestoreState(savedInstanceState);
    }

    private void doRestoreState(final Bundle savedInstanceState) {
        if (savedInstanceState == null) return;
        getTextView(R.id.person_editor).setText(getNotNull(savedInstanceState.getString(PROPERTY_PERSON)));
        getTextView(R.id.quantity_editor).setText(getNotNull(savedInstanceState.getString(PROPERTY_QUANTITY)));
        getTextView(R.id.subject_editor).setText(getNotNull(savedInstanceState.getString(PROPERTY_SUBJECT)));
        getTextView(R.id.comment_editor).setText(getNotNull(savedInstanceState.getString(PROPERTY_COMMENT)));
    }

    private String getNotNull(final String string) {
        return string == null ? "" : string;
    }

    @Override
    protected void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(PROPERTY_PERSON, getTextView(R.id.person_editor).getText().toString());
        outState.putString(PROPERTY_QUANTITY, getTextView(R.id.quantity_editor).getText().toString());
        outState.putString(PROPERTY_SUBJECT, getTextView(R.id.subject_editor).getText().toString());
        outState.putString(PROPERTY_COMMENT, getTextView(R.id.comment_editor).getText().toString());
    }

    private TextView getTextView(final int editorId) {
        return (TextView) getActualView(findViewById(editorId));
    }

    @Override
    public boolean onPrepareOptionsMenu(final Menu menu) {
        menu.findItem(R.id.settings_menu_item).setVisible(true);
        return super.onPrepareOptionsMenu(menu);
    }

    private void saveRecord(final boolean stayActive) {
        final String person = getTrimmedEditorText(R.id.person_editor);
        if (person.length() == 0) {
            showShortToast(R.string.person_must_not_be_empty);
            focus(R.id.person_editor);
            return;
        }

        final String quantityStr = getTrimmedEditorText(R.id.quantity_editor);
        if (quantityStr.length() == 0) {
            showShortToast(R.string.quantity_must_not_be_empty);
            focus(R.id.quantity_editor);
            return;
        }

        final Integer quantity = parseInteger(quantityStr);
        if (quantity == null) {
            showShortToast(R.string.is_not_a_number, quantityStr);
            focus(R.id.quantity_editor);
            return;
        }

        if (quantity < 0) {
            showShortToast(R.string.quantity_must_not_be_less_than_zero);
            focus(R.id.quantity_editor);
            return;
        }

        if (quantity == 0) {
            showShortToast(R.string.quantity_must_not_be_equal_to_zero);
            focus(R.id.quantity_editor);
            return;
        }

        final String subject = getTrimmedEditorText(R.id.subject_editor);
        if (subject.length() == 0) {
            showShortToast(R.string.subject_must_not_be_empty);
            focus(R.id.subject_editor);
            return;
        }

        final String comment = getTrimmedEditorText(R.id.comment_editor);

        DataUtil.perfromDataAction(this, R.string.saving, new DataProcessor<Void>() {
            public Void process(final DataManager dataManager) {
                dataManager.addDebt(myRecordType, person, subject, quantity, comment);
                return null;
            }
        }, new DataActionResultProcessor<Void>() {
            public Void process(final Void v) {
                showShortToast(R.string.the_debt_was_successfully_saved);

                if (stayActive) {
                    focus(R.id.person_editor);
                } else {
                    finish();
                }

                return null;
            }
        });
    }
}
